<template>
    <div style="width:35rem">
        <editor
           :api-key="apiKey"
           :init="editConfig"
           v-model="content"
         />
    </div>
</template>

<script>
import axios from 'axios'
import Editor from '@tinymce/tinymce-vue'
export default {
    components: {
      'editor': Editor
    },
    data() {
        return {
            qnToken:"",
            imgLoadPercent:0,
            content: "",
            apiKey: "fpj87ro4rvzp97s3tpiwsehhcpoid9ceaz74mkbwop3jkmkc", //key值从官网注册申请来的
            editConfig: {
              height: 500, //富文本高度
              language_url: '/tinymce/zh_CN.js', //中文包
              language: 'zh_CN', //中文
              browser_spellcheck: true, // 拼写检查
              branding: false, // 去水印
              elementpath: true, //禁用编辑器底部的状态栏
              statusbar: true, // 隐藏编辑器底部的状态栏
              
              menubar: true, // 隐藏最上方menu
              fontsize_formats: '14px 16px 18px 20px 24px 26px 28px 30px 32px 36px', //字体大小
              font_formats:'微软雅黑=Microsoft YaHei,Helvetica Neue;PingFang SC;sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun;serifsans-serif;Terminal=terminal;monaco;Times New Roman=times new roman;times', //字体
              file_picker_types: 'image',
              images_upload_credentials: true,

              // 设置: 复制粘贴
              paste_retain_style_properties: 'all',
              paste_word_valid_elements: '*[*]', //word需要它
              paste_convert_word_fake_lists: false, // 插入word文档需要该属性
              paste_data_images: true, // 是否允许粘贴图像
              paste_webkit_styles: 'all',
              paste_merge_formats: true,
              nonbreaking_force_tab: false,
              paste_auto_cleanup_on_paste: false,

              plugins: [
                'a11ychecker advcode advlist anchor autolink codesample fullscreen help image imagetools tinydrive',
                ' lists link media noneditable powerpaste preview',
                ' searchreplace table template tinymcespellchecker visualblocks wordcount'
              ],
              toolbar: 'fontselect fontsizeselect link lineheight forecolor backcolor bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | image quicklink h2 h3 blockquote table numlist bullist preview fullscreen',
              images_upload_handler: (blobInfo, success, failure) => {
                const axiosInstance = axios.create({ withCredentials: false }); //withCredentials 禁止携带cookie，带cookie在七牛上有可能出现跨域问题
                const data = new FormData();
                data.append("token", this.qnToken); //七牛需要的token，后台获取
                data.append("file", blobInfo.blob());
                axiosInstance({
                    method: "POST",
                    url: 'https://up-z2.qiniup.com', //上传地址，视情况更换
                    data: data,
                    timeout: 10000, //超时时间，因为图片上传有可能需要很久
                    onUploadProgress: progressEvent => {
                      //imgLoadPercent 是上传进度，可以用来添加进度条
                      this.imgLoadPercent = Math.round(
                                (progressEvent.loaded * 100) / progressEvent.total
                            );
                        }
                    }).then(res => {
                        // 调用成功回调，返回用七牛外链地址和返回的key拼接的图片路径
                        success(`http://file.szuet.ltd/${res.data.key}`);
                    }).catch(e=>{
                      console.log(failure)
                        if(e.response.staus==='401'){
                                this.$message({
                                    type:'warning',
                                    message:"鉴权失败！"
                                })
                            }
                        else if(e.response.state==='400'){
                              this.$message({
                                    type:'warning',
                                    message:"请求报文格式错误！"
                                })
                            }
                          });
                }
              }
            }
        },
    methods: {
      async getUploadToken() {
        const res = await this.$http.get('/upload') //更换自己的请求方法和路径
        this.qnToken = res.data.upToken
      },
    },
    computed: {
      getArticleContent(){
          return this.$store.state.article_content
        }
    },
    watch: {
      content(now){
        this.$store.commit('setArticleContent',now)
      },
      getArticleContent(newInfo){
				this.content = newInfo
			}
      },
    created(){
          this.getUploadToken()
          this.content = console.log(this.$store.state.article_content)
      },
    }
</script>